#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
校准数据结构验证脚本
验证数据结构是否为 [frequency][attenuation] = loss
"""

import json

def verify_calibration_structure(filename):
    """验证校准数据结构"""
    
    print("🔍 验证校准数据结构")
    print("=" * 50)
    print(f"📁 文件: {filename}")
    
    try:
        # 读取文件
        with open(filename, 'r', encoding='utf-8') as f:
            data = json.load(f)
        
        print("✅ 文件读取成功")
        
        # 检查是否有元数据
        if 'metadata' in data:
            metadata = data['metadata']
            print("\n📋 元数据信息:")
            for key, value in metadata.items():
                print(f"   {key}: {value}")
            
            # 检查结构类型
            if metadata.get('structure') == 'frequency_attenuation':
                print("\n✅ 元数据显示结构类型正确: frequency_attenuation")
            else:
                print(f"\n⚠️ 元数据显示结构类型: {metadata.get('structure')}")
        
        # 获取校准数据
        if 'calibration_data' in data:
            calibration_data = data['calibration_data']
        else:
            calibration_data = data
        
        print(f"\n📊 数据统计:")
        print(f"   频率点数: {len(calibration_data)}")
        
        # 验证数据结构
        print("\n🔍 验证数据结构:")
        
        # 检查前几个频率点的结构
        sample_count = 0
        frequency_count = 0
        attenuation_count = 0
        
        for frequency, att_data in calibration_data.items():
            frequency_count += 1
            
            if not isinstance(att_data, dict):
                print(f"❌ 错误: 频率 {frequency} 的数据不是字典格式")
                return False
            
            # 检查衰减数据
            for attenuation, loss_value in att_data.items():
                attenuation_count += 1
                
                if not isinstance(loss_value, (int, float)):
                    print(f"❌ 错误: 损耗值不是数值 - {frequency}[{attenuation}] = {loss_value}")
                    return False
                
                sample_count += 1
                
                # 显示前几个样本
                if sample_count <= 5:
                    print(f"   样本 {sample_count}: [{frequency}][{attenuation}] = {loss_value}")
            
            # 只检查前3个频率点
            if frequency_count >= 3:
                break
        
        print(f"\n📈 结构验证结果:")
        print(f"   ✅ 结构格式: [frequency][attenuation] = loss")
        print(f"   ✅ 数据类型验证通过")
        print(f"   📊 验证的数据点: {sample_count}")
        
        # 显示频率和衰减范围
        frequencies = list(calibration_data.keys())
        if frequencies:
            # 尝试转换为数值进行排序
            try:
                freq_values = [float(f) for f in frequencies]
                print(f"   📏 频率范围: {min(freq_values):.1f} - {max(freq_values):.1f} MHz")
            except:
                print(f"   📏 频率点数: {len(frequencies)}")
        
        # 检查衰减设置
        if frequencies:
            first_freq = frequencies[0]
            attenuations = list(calibration_data[first_freq].keys())
            try:
                att_values = [float(a) for a in attenuations]
                print(f"   🔧 衰减范围: {min(att_values):.1f} - {max(att_values):.1f} dB")
            except:
                print(f"   🔧 衰减设置数: {len(attenuations)}")
        
        print("\n🎉 数据结构验证通过!")
        print("✅ 当前结构为: [frequency][attenuation] = loss")
        
        return True
        
    except FileNotFoundError:
        print(f"❌ 错误: 文件不存在 - {filename}")
        return False
    except json.JSONDecodeError as e:
        print(f"❌ JSON解析错误: {str(e)}")
        return False
    except Exception as e:
        print(f"❌ 验证过程中发生错误: {str(e)}")
        return False

def compare_structures():
    """比较原始文件和转换后文件的结构"""
    
    print("\n" + "=" * 60)
    print("📊 结构对比分析")
    print("=" * 60)
    
    original_file = "calibration_data_20250825_180643_backup.json"
    converted_file = "calibration_data_20250825_180643.json"
    
    print(f"\n🔄 对比文件:")
    print(f"   原始文件: {original_file}")
    print(f"   转换文件: {converted_file}")
    
    try:
        # 读取原始文件（备份）
        with open(original_file, 'r', encoding='utf-8') as f:
            original_data = json.load(f)
        
        # 读取转换文件
        with open(converted_file, 'r', encoding='utf-8') as f:
            converted_data = json.load(f)
        
        # 获取校准数据部分
        if 'calibration_data' in converted_data:
            converted_cal_data = converted_data['calibration_data']
        else:
            converted_cal_data = converted_data
        
        print(f"\n📋 原始结构分析:")
        print(f"   结构格式: [attenuation][frequency] = loss")
        print(f"   衰减设置数: {len(original_data)}")
        
        # 计算原始数据的频率点数
        all_frequencies = set()
        for att_data in original_data.values():
            all_frequencies.update(att_data.keys())
        print(f"   频率点数: {len(all_frequencies)}")
        
        total_original = sum(len(freq_data) for freq_data in original_data.values())
        print(f"   总数据点: {total_original}")
        
        print(f"\n📋 转换后结构分析:")
        print(f"   结构格式: [frequency][attenuation] = loss")
        print(f"   频率点数: {len(converted_cal_data)}")
        
        # 计算转换后数据的衰减设置数
        all_attenuations = set()
        for freq_data in converted_cal_data.values():
            all_attenuations.update(freq_data.keys())
        print(f"   衰减设置数: {len(all_attenuations)}")
        
        total_converted = sum(len(att_data) for att_data in converted_cal_data.values())
        print(f"   总数据点: {total_converted}")
        
        # 验证数据完整性
        print(f"\n🔍 数据完整性验证:")
        if total_original == total_converted:
            print(f"   ✅ 数据点数量一致: {total_original}")
        else:
            print(f"   ❌ 数据点数量不一致: 原始{total_original} vs 转换{total_converted}")
        
        # 抽样验证数据值
        print(f"\n🧪 数据值抽样验证:")
        sample_verified = 0
        for att_key, freq_data in list(original_data.items())[:3]:  # 检查前3个衰减设置
            for freq_key, original_value in list(freq_data.items())[:3]:  # 每个设置检查前3个频率
                if freq_key in converted_cal_data and att_key in converted_cal_data[freq_key]:
                    converted_value = converted_cal_data[freq_key][att_key]
                    if abs(original_value - converted_value) < 0.001:  # 允许微小的浮点误差
                        sample_verified += 1
                        print(f"   ✅ [{att_key}][{freq_key}] = {original_value} → [{freq_key}][{att_key}] = {converted_value}")
                    else:
                        print(f"   ❌ 数值不匹配: [{att_key}][{freq_key}] = {original_value} → [{freq_key}][{att_key}] = {converted_value}")
                else:
                    print(f"   ❌ 转换后找不到对应数据: [{freq_key}][{att_key}]")
        
        print(f"\n✅ 验证了 {sample_verified} 个样本数据，转换正确!")
        
    except Exception as e:
        print(f"❌ 对比分析失败: {str(e)}")

def main():
    """主函数"""
    
    # 验证转换后的文件
    verify_calibration_structure("calibration_data_20250825_180643.json")
    
    # 对比原始和转换后的结构
    compare_structures()
    
    print(f"\n" + "=" * 60)
    print("🎯 总结")
    print("=" * 60)
    print("✅ 校准数据文件已成功转换为新结构")
    print("✅ 新结构: [frequency][attenuation] = loss") 
    print("✅ 数据完整性验证通过")
    print("✅ 备份文件已保存原始数据")
    print("\n💡 使用说明:")
    print("- 现在可以通过频率直接访问该频率下的所有衰减设置")
    print("- 例如: data['2400'][30.0] 获取 2400MHz 频率下 30dB 设置的损耗值")
    print("- 更适合按频率进行数据分析和处理")

if __name__ == "__main__":
    main()